#!/usr/bin/env python
# -*- coding:utf-8 -*-

from controller.userController import UserController
from app import db
from utils.response_code import RET, error_map_EN
from utils import commons
from models.userModel import User

class UserService(UserController):
    
    @classmethod
    def login(cls, **kwargs):
        account = kwargs.get("Account")
        password = kwargs.get("Password")
        try:
            filter_list = [cls.IsDelete == 0]
            if account:
                filter_list.append(cls.Account == account)
            user_info = db.session.query(cls).filter(*filter_list).first()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data':{'error': "数据库连接异常,登录失败"}}

        # 验证用户是否存在
        if not user_info:
            return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'data': {'error': '用户不存在'}}

        user_info_data = commons.query_to_dict(user_info)

        # 校验密码
        try:
            if password != user_info_data.get("Password"):
                return {'code': RET.LOGINERR, 'message': error_map_EN[RET.LOGINERR], 'data': {'error': "密码错误"}}
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常，密码查验失败"}}

        result = {
            'UserName': user_info_data.get("UserName"),
            'Account': user_info_data.get("Account"),
            'UserID': user_info_data.get("UserID")
        }
        return {'code': RET.OK, 'message': error_map_EN[RET.OK], "data": result}

    # 用户注册
    @classmethod
    def register(cls, **kwargs):
        # 判断用户是否存在
        try:
            user_info = db.session.query(cls).filter(cls.Account == kwargs.get("Account")).first()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data':{'error': "数据库连接异常"}}

        if user_info:
            return {'code': RET.DATAEXIST, 'message': error_map_EN[RET.DATAEXIST], 'data':{'error': "该用于已经注册"}}

        try:
            from utils.generate_id import GenerateID
            UserID = GenerateID.create_id_by_autoID()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常,生成ID错误"}}

        try:
            model = User(
                UserID=int(UserID),
                Account=kwargs.get("Account"),
                Password=kwargs.get("Password"),
                UserName=kwargs.get("UserName")
            )
            db.session.add(model)
            db.session.commit()
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': error_map_EN[RET.OK]}
        except Exception as e:
            db.session.rollback()
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常"}}
        finally:
            db.session.close()